#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

void printLoop(const vector<vector<int>> &matrix, const int &begin, const int &rows, const int &cols) {
  int end_row = rows - begin;
  int end_col = cols - begin;
  for (int i = begin; i < end_col; ++i) {
    cout << matrix[begin][i] << " ";
  }
  for (int i = begin + 1; i < end_row; ++i) {
    cout << matrix[i][end_col - 1] << " ";
  }
  if (rows - 2 * begin >= 2) {
    for (int i = end_col - 2; i >= begin; --i) {
      cout << matrix[end_row - 1][i] << " ";
    }
  }
  if (cols - 2 * begin >= 2) {
    for (int i = end_row - 2; i > begin; --i) {
      cout << matrix[i][begin] << " ";
    }
  }
}

void printMatrix(const vector<vector<int>> &matrix) {
  auto rows = matrix.size();
  auto cols = matrix[0].size();
  for (auto i = 0; i * 2 < rows && i * 2 < cols; ++i) {
    printLoop(matrix, i, rows, cols);
  }
}

int main() {
  vector<vector<int>> input_vec = {{1, 2, 3, 4},
                                   {5, 6, 7, 8},
                                   {9, 10, 11, 12},
                                   {13, 14, 15, 16}};
  printMatrix(input_vec);
  cout << endl;

  input_vec = {{1, 2, 3, 4, 5},
               {6, 7, 8, 9, 10},
               {11, 12, 13, 14, 15},
               {16, 17, 18, 19, 20},
               {21, 22, 23, 24, 25}};
  printMatrix(input_vec);
  cout << endl;

  input_vec = {{1, 2, 3, 4, 5},
               {6, 7, 8, 9, 10},
               {11, 12, 13, 14, 15},
               {16, 17, 18, 19, 20}};
  printMatrix(input_vec);
  cout << endl;

  input_vec = {{1, 2, 3, 4},
               {5, 6, 7, 8},
               {9, 10, 11, 12},
               {13, 14, 15, 16},
               {17, 18, 19, 20}};
  printMatrix(input_vec);
  cout << endl;

  input_vec = {{1, 2, 3},
               {4, 5, 6},
               {7, 8, 9},
               {10, 11, 12},
               {13, 15, 16}};
  printMatrix(input_vec);
  cout << endl;

  input_vec = {{1, 2, 3, 4},
               {5, 6, 7, 8},
               {9, 10, 11, 12}};
  printMatrix(input_vec);
  cout << endl;

  return 0;
}
